import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {Button, Radio, Select, Input, Table, Modal, Form, message, Tooltip} from 'antd';

import {defaultPagination, Search, TableBtn} from '../publicComponents';
import {get, post} from "../../../utils";
import {mUrl} from "../../../config";
import {PlusOutlined} from "@ant-design/icons";

const {Option} = Select;

const Page = () => {
    const [row, setRow] = useState({}); // 点击表格按钮要把那一行的数据传送到弹框中
    const [dataSource, setDataSource] = useState([]); // 表格内容信息
    const [searchDetail, setSearchDetail] = useState({}); // 表格内容信息
    const [pagination, setPagination] = useState(Object.assign({}, defaultPagination)); // 表格分页
    const [visible, setVisible] = useState(false); // 开通画册弹框
    const [options, setOptions] = useState([]); // 分类列表
    const [parentid, setParentId] = useState('');
    
    const columns = [
        {
            title: '序号',
            align: 'center',
            key: 'orgid',
            dataIndex: 'orgid',
            width: 80,
            fixed: true,
            render: (text, record, index) => ((pagination.pageSize * (pagination.current ? pagination.current - 1 : 0)) + index + 1)
        },
        {
            title: '操作',
            align: 'center',
            fixed: true,
            width: 100,
            render: (text, record, index) => {
                return (
                    <TableBtn
                        record={record}
                        onClick={handleTableBtnClick}
                        btns={[
                            {id: 1, name: '审核', hidden: (record.orgstate !== 0 && record.orgstate !== -3)},
                            {
                                id: 2,
                                name: record.orgstate === -1 ? '启用' : '停用',
                                hidden: (record.orgstate !== 1 && record.orgstate !== -1)
                            },
                        ]}
                    />
                );
            }
        },
        {
            title: '分类',
            align: 'center',
            dataIndex: 'orgClassifyList',
            width: 100,
            render: (orgClassifyList = []) => {
                let text = orgClassifyList.map((item) => item.name).join('/') || '--';
                return (
                    <Tooltip placement={'topLeft'} title={text}>
                        {text.length > 15 ? text.substr(0, 15) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '状态',
            align: 'center',
            dataIndex: 'orgstate',
            width: 100,
            render: orgstate => {
                let text = '';
                //(1:已通过；0：待认证；-1：已停用；-2：已删除；-3：未通过)
                switch (orgstate) {
                    case 0:
                        text = '待认证';
                        break;
                    case 1:
                        text = '已通过';
                        break;
                    case -1:
                        text = '已停用';
                        break;
                    case -2:
                        text = '已删除';
                        break;
                    case -3:
                        text = '未通过';
                        break;
                    default:
                }
                return text;
            }
        },
        {
            title: '主图',
            align: 'center',
            width: 100,
            render: (data, record, index) => {
                if (data.imageurl) {
                    if (data.show) {
                        const image = data.imageurl.split(',');
                        return (
                            <div>
                                <img style={{width: 80}} src={image[0]} alt=""/>
                            </div>
                        );
                    } else {
                        return <span 
                            style={{color:'#0da8de',cursor:'pointer'}}
                            className={'span-selected'}
                            onClick={() => {
                            dataSource[index].show = true;
                            setDataSource(Object.assign([], dataSource));
                        }}>显示图片</span>;
                    }
                }
                return '--';
            }
        },
        {
            title: '经销商名称',
            align: 'center',
            dataIndex: 'orgname',
            width: 150,
            render: orgaddress => {
                let text = orgaddress || '--';
                return (
                    <Tooltip placement={'topLeft'} title={orgaddress}>
                        {text.length > 6 ? text.substr(0, 6) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '联系人',
            align: 'center',
            dataIndex: 'linkman',
            width: 120,
            render: linkman => {
                return linkman || '--';
            }
        },
        {
            title: '联系方式',
            align: 'center',
            dataIndex: 'linkphone',
            width: 120,
            render: linkphone => {
                return linkphone || '--';
            }
        },
        {
            title: '地址',
            align: 'center',
            dataIndex: 'orgaddress',
            width: 150,
            render: orgaddress => {
                let text = orgaddress || '--';
                return (
                    <Tooltip placement={'topLeft'} title={orgaddress}>
                        {text.length > 6 ? text.substr(0, 6) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '简介',
            align: 'center',
            dataIndex: 'remark',
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 6 ? text.substr(0, 6) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '营业执照',
            align: 'center',
            render: (data, record, index) => {
                if (data.businessurl) {
                    if (data.businessShow) {
                        const image = data.businessurl.split(',');
                        return (
                            <div>
                                <img style={{width: 80}} src={image[0]} alt=""/>
                            </div>
                        );
                    } else {
                        return <span
                            style={{color:'#0da8de',cursor:'pointer'}}
                            className={'span-selected'}
                            onClick={() => {
                            dataSource[index].businessShow = true;
                            setDataSource(Object.assign([], dataSource));
                        }}>显示图片</span>;
                    }
                }
                return '--';
            }
        },
        {
            title: '备注',
            align: 'center',
            dataIndex: 'checkremark',
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 6 ? text.substr(0, 6) + '...' : text}
                    </Tooltip>
                );
            }
        },
    ];

    useEffect(() => {
        searchTypeList();
        fetch();
    }, []);
    
    const searchTypeList = () => {
        get(mUrl.searchAllClassify, {}).then((res) => {
            const data = res.data.map((item) => {
                const list = item.subClassifyList.map((sItem) => {
                    return {
                        value: sItem.classifyid,
                        label: sItem.name,
                    };
                });
                return {
                    value: item.classifyid,
                    label: item.name,
                    children: list
                };
            });
            setOptions(data);
        });
    };
    
    const fetch = (params = {}) => {
        let start = 1;
        if (params.startList > 1) {
            start = params.startList;
        }
        get(mUrl.searchOrganizationList, {
            pageNo: start,
            orgtype: 2,
            pageSize: pagination.pageSize, ...params
        }).then((res) => {
            const {list = [], count = 0} = res.data;
            pagination.total = count;
            setPagination(pagination);
            setDataSource(list);
            setSearchDetail(params);
        });
    };

    const handleTableBtnClick = (id, record) => {
        setRow(record);
        if (id === 1) {
            setVisible(true);
        } else if (id === 2) {
            let text = record.orgstate === -1 ? '启用' : '停用';
            let orgstate = record.orgstate === -1 ? 1 : -1;
            Modal.confirm({
                title: '提示',
                content: '是否要' + text + '该经销商',
                onOk: () => {
                    handleUpdateDetail({
                        ...record,
                        orgstate,
                    }, () => {
                        message.success(text + '成功');
                    });
                }
            });
        }
    };

    const handleUpdateDetail = async (value, callback) => {
        const data = Object.assign({}, row, value);
        const res = await post(mUrl.updateOrganization, data);
        if (res.state === 1) {
            callback();
            fetch(searchDetail);
        }
    };

    const handleTableChange = (page) => {
        pagination.current = page.current;
        pagination.pageSize = page.pageSize;
        setPagination(pagination);
        fetch({
            startList: pagination.current,
            ...searchDetail,
        });
    };

    const onSearch = (value) => {
        if (value.classify) {
            value.classifyid = value.classify;
        } else {
            value.classifyid = undefined;
        }
        delete value.classify;
        fetch(value);
    };
    
    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>经销商管理 / 经销商列表</p></label>
            <Search
                searchData={[
                    {span: 4, labelCol: 6, key: 'classify', name: '分类', component: (
                        <Select
                            placeholder="请选择"
                            showSearch={true}
                            options={options}
                        />)
                    },
                    {span: 6, labelCol: 6, key: 'orgname', name: '经销商', component: (
                        <Input allowClear placeholder="经销商名称/联系人/联系方式"/>
                        )
                    },
                    {span: 4, labelCol: 6, key: 'orgstate', name: '状态', component: (
                            <Select placeholder={'请选择'}>
                                <Option value={''}>全部</Option>
                                <Option value={'1'}>已通过</Option>
                                <Option value={'0'}>待认证</Option>
                                <Option value={'-1'}>已停用</Option>
                                <Option value={'-3'}>未通过</Option>
                            </Select>
                        )
                    }
                ]}
                otherBtns={[
                    {name: '导出'}
                ]}
                onReset={() => {
                    fetch({});
                }}
                // onSearch={(form) => {
                //     form.validateFields().then(values => console.log(values));
                // }}
                onSearch={onSearch}
            />
            <Button
                type={'primary'}
                style={{margin: '-5px 0 10px 0'}}
                onClick={() => window.onSelectWin({title: '新增经销商', path: '/main/addDistributor', page: '/main/addDistributor'})}
            >
                <PlusOutlined/>新增经销商
            </Button>
            <Table
                rowKey={(record) => {
                    return record.orgid;
                }}
                scroll={{x: 1400, y: 600}}
                dataSource={dataSource}
                columns={columns}
                bordered
                pagination={pagination}
                onChange={handleTableChange}
                rowClassName={(record) => {
                    if (record.orgid === parentid) {
                        return 'table-select-type';
                    } else {
                        return 'table-type';
                    }
                }}
                onRow={record => {
                    return {
                        onClick: event => {
                            setParentId(record.orgid);
                        },
                    };
                }}
            />
            <Examine
                visible={visible}
                setVisible={setVisible}
                submit={handleUpdateDetail}
            />
        </div>
    );
};

// 点击审核的弹框
const Examine = (props) => {
    const [form] = Form.useForm();
    const {visible = false, setVisible} = props;
    const [checkremark, setCheckremark] = useState(null);
    const [orgstate, setOrgstate] = useState(null);
    
    const onFinish = (value) => {
        if (!value.select) {
            message.warning('请选择是否开通');
            return;
        }
        const orgstate = value.select;
        const checkremark = value.remark;
        console.log(orgstate,checkremark);
        props.submit({
            orgstate,
            checkremark
        },()=>{
            message.success('审核成功');
            setVisible(false);
        });
    };
    return (
        <Modal
            visible={visible}
            onCancel={_ => setVisible(false)}
            footer={null}
            getContianer={false}
        >
            <Form form={form} onFinish={onFinish}>
                <Form.Item name={'select'} label='审核'>
                    <Radio.Group value={orgstate} onChange={(e) => setOrgstate(e.target.value)}>
                        <Radio value={1}>通过</Radio>
                        <Radio value={-3}>不通过</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item name={'remark'} label='备注'>
                    <Input.TextArea value={checkremark}
                                    onChange={(e) => setCheckremark(e.target.value)}/>
                </Form.Item>
                <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                    <Button
                        htmlType="submit" 
                        type={'primary'}
                    >提交</Button>
                    <Button style={{marginLeft: 15}}
                            onClick={_ => setVisible(false)}
                    >取消</Button>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default connect()(Page);